using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using eShop.Business;
using ECommerce.Library.ECommerce;
using eShop.Utility;
using eShop.Model;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using System.IO;
using System.Threading.Tasks;
using eShop.Model.MetaData;

public partial class order_summary : SitePublicBasePage
{

    private Double _ORDER_SHIPPING_COST
    {
        get
        {
            try
            {
                return Convert.ToDouble(ViewState["_ORDER_SHIPPING_COST"]);
            }
            catch
            {
                return 0;
            }
        }
        set
        {
            ViewState["_ORDER_SHIPPING_COST"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        uccResponseMessage.Visible = false;
        if (!Page.IsPostBack)
        {
            ValidateOrderConfirmationStep();
            BindData();
        }
        aShippingAddress.OnAddressChanged += ShippingAddressChanged;
    }

    private void ValidateOrderConfirmationStep()
    {
        if (ShoppingCartManager.HasAnyItemInCart() == false
            || SessionManager.CheckoutSteps < CheckoutSteps.PreCheckout)
        {
            Response.Redirect(eShop.Business.CustomSiteMap.ShoppingCart);
        }
    }

    protected void BindData()
    {
        aShippingAddress.DataSource = null;
        aShippingAddress.DataBind();
        if (SessionManager.IsUserLoggedIn)
        {
            User user = SessionManager.LoggedUser;

            phUserInformation.Visible = false;
            phAddressSelector.Visible = true;
            BindUserAddressBook(user.Id, null);
            //BindShippingAddressByUserAddressBook(Convert.ToInt32(ddlAddressBookList.SelectedValue));
        }
        else
        {
            phUserInformation.Visible = true;
            phAddressSelector.Visible = false;
        }
        BindOrderInformation(ShoppingCartManager.GetCart(), aShippingAddress.DataSource);
    }

    protected void PlaceOrderOnline_Click(object sender, EventArgs e)
    {
        Order order = null;
        
        try
        {
            if (Page.IsValid)
            {
                Cart cart = ShoppingCartManager.GetCart();
                order = new Order();
                order.OrderDate = DateTime.Now;
                order.OrderStatus = OrderStatusType.CCFail;
                
                if (SessionManager.IsUserLoggedIn)
                {
                    User user = SessionManager.LoggedUser;
                    order.UserId = user.Id;
                    order.Name = user.Profile.FullName;
                    order.EmailAddress = user.Profile.EmailAddress;
                }
                else
                {
                    order.UserId = 0;
                    order.Name = tbFullName.Text.Trim();
                    order.EmailAddress = tbEmailAddress.Text.Trim();
                }

                foreach (CartItem cartItem in cart.CartItems)
                {
                    ProductManager.ReduceStock(cartItem.Stock.StockId, cartItem.Quantity);
                    if (StockAlert.IsStockAlert(cartItem.Stock.StockId))
                    {
                        StockAlert alert = StockAlert.Load(cartItem.Stock.StockId);
                        StockAlert.SendStockAlertEmail(alert);
                    }
                    
                    order.OrderItems.Add(new OrderItem(cartItem));
                }

                order.PaymentType = (PaymentType)Enum.Parse(typeof(PaymentType), ddlPaymentMethod.SelectedItem.Value);
                order.PaymentStatus = string.Empty;
                order.SpecialInstruction = HttpContext.Current.Server.HtmlEncode(tbxComment.Text);
                order.OrderNumber = SiteSettings.OrderPrefix;
                order.SubTotal = cart.CartItems.SubTotal;
                
                aShippingAddress.DataRead();
                order.ShippingAddress = aShippingAddress.DataSource;
                order.ShippingStatus = ShippingStatusType.NotShipped;
                order.ShippingCost = _ORDER_SHIPPING_COST;

                if (OrderManager.CreateOrder(order))
                {
                    SessionManager.OrderNumber = order.OrderNumber;
                    SessionManager.OrderID = order.OrderId;
                    ShoppingCartManager.ClearCart();
                    SessionManager.CheckoutSteps = CheckoutSteps.OrderSummary;
                    if (order.PaymentType == PaymentType.bKash)
                    {
                        HttpContext.Current.Response.Redirect("~/confirm-order.aspx",false);
                    }
                    else if (order.PaymentType == PaymentType.CreditCard)
                    {
                        string _amt = order.TotalAmount.ToString();
                        string _tran = order.OrderNumber;
                        string _succUrl = SiteGlobals.BaseUrl + string.Format("confirm-order.aspx?id={0}&tran_status={1}", order.OrderId, Imgalib.Utility.Cryptography.EncryptStringAES("success"));
                        string _failUrl = SiteGlobals.BaseUrl + string.Format("confirm-order.aspx?id={0}&tran_status={1}", order.OrderId, Imgalib.Utility.Cryptography.EncryptStringAES("fail"));
                        string _cancelUrl = SiteGlobals.BaseUrl + string.Format("confirm-order.aspx?id={0}&tran_status={1}", order.OrderId, Imgalib.Utility.Cryptography.EncryptStringAES("cancel"));
                        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "NavigateToSSLCommerz('" + _amt + "','" + _tran + "','" + _succUrl + "','" + _failUrl + "','" + _cancelUrl + "');", true);
                    }
                    else
                    {
                        //Do Nothing
                    }
                }
            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(ex.Message);
            if (order != null && order.OrderId > 0)
            {
                OrderManager.DeleteOrderById(order.OrderId);
            }
        }
    }

    private void BindUserAddressBook(int userId, int? defaultAddress)
    {
        ddlAddressBookList.DataSource = AddressManager.GetAddressesByUserId(userId);
        ddlAddressBookList.DataTextField = "Name";
        ddlAddressBookList.DataValueField = "Id";
        ddlAddressBookList.DataBind();
        if (defaultAddress.HasValue)
            ddlAddressBookList.SelectedValue = defaultAddress.ToString();
    }

    private void BindShippingAddressByUserAddressBook(int addressBookId)
    {
        aShippingAddress.DataSource = AddressManager.GetAddressById(addressBookId);
        aShippingAddress.DataBind();
    }

    private void BindOrderInformation(Cart cart, Address shippingAddress)
    {
        if (shippingAddress != null)
        {
            double shippingCost = ShippingRateManager.GetShippingRateByCountryStateCityWeight(shippingAddress.City, shippingAddress.State, shippingAddress.Country, (float)cart.CartItems.TotalWeight);
            double totalPrice = cart.CartItems.SubTotal + shippingCost;
            _ORDER_SHIPPING_COST = shippingCost;
            lblShippingCost.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(shippingCost);
            lblTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(totalPrice);
        }
        else
        {
            _ORDER_SHIPPING_COST = 0;
            lblShippingCost.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(0.00);
            lblTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cart.CartItems.SubTotal);
        }
    }

    protected void ddlAddressBookList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindShippingAddressByUserAddressBook(Convert.ToInt32(ddlAddressBookList.SelectedValue));
    }

    protected void ShippingAddressChanged(object sender, Address address)
    {
        BindOrderInformation(ShoppingCartManager.GetCart(), address);
    }

}
